<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisible.addRolesDialogVisible = true">添加角色</el-button>
        </el-col>
        <el-col>
          <!-- 表格区域 -->
          <el-table :data="rolesList" stripe border>
            <!-- 前面展开列区域 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-row :class="['bdtop', index1 === 0 ? 'bdbottom' : '', 'vcenter']" v-for="(item1, index1) in scope.row.children" :key="item1.id">
                  <el-col :span="5">
                    <!-- 渲染一级权限 -->
                    <el-tag closable @close="removeRightById(scope.row, item1.id)"> {{ item1.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染二级权限与三级权限 -->
                  <el-col :sapn="19">
                    <el-row :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, index2) in item1.children" :key="item2.id">
                      <el-col :span="6">
                        <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                        <!-- 右箭头标 -->
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <el-col :span="18">
                        <el-tag :class="[index3 === 0 ? '' : 'bptop']" v-for="(item3, index3) in item2.children" :key="item3.id" type="warning" closable @close="removeRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="roleName" label="角色名称"> </el-table-column>
            <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <!-- 编辑按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="setEditRolesDialogVisible(scope.row.id)">编辑</el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRolesById(scope.row.id)">删除</el-button>
                <!-- 分配按钮 -->
                <!-- 将整行放进去进行分配, 整行数据有id -->
                <el-button type="warning" icon="el-icon-search" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- 添加用户按钮 -->
    </el-card>
    <!-- 对话框区域 -->
    <!-- 添加用户对话框区域 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible.addRolesDialogVisible" width="30%" @close="resetAddRolesDialog">
      <el-form label-width="80px" :model="addRolesDialogForm" :rules="addRolesRules" ref="addRolesRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesDialogForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesDialogForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框区域 -->
    <el-dialog title="编辑角色" :visible.sync="dialogVisible.editRolesDialogVisible" width="30%" @close="resetEditRolesDialog">
      <el-form label-width="80px" :model="editRolesDialogForm" :rules="editRolesRules" ref="editRolesRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesDialogForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesDialogForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible.editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框区域 -->
    <el-dialog title="分配角色" :visible.sync="dialogVisible.setRightDialogVisible" width="30%" @close="setRightDialogVisibleClosed">
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="defKeys" ref="treeRef"> </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible.setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getRolesList();
  },
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 控制对话框显示隐藏
      dialogVisible: {
        addRolesDialogVisible: false,
        editRolesDialogVisible: false,
        setRightDialogVisible: false,
      },
      // 添加用户框数据
      addRolesDialogForm: {
        roleName: "",
        roleDesc: "",
      },
      // 添加用户框数据验证规则
      addRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
        ],
      },
      // 编辑用户对话框数据
      editRolesDialogForm: {},
      editRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
        ],
      },
      // 分配权限的权限列表数据，树型结构
      rightsList: [],
      // 树形控件的绑定对象
      treeProps: {
        children: "children",
        label: "authName",
      },
      // 树形控件 -> 默认选中的节点id值数组
      defKeys: [],
      // 当前即将分配权限的角色的ID
      rolesId: "",
    };
  },
  methods: {
    // 获取角色权限列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      } else {
        this.rolesList = res.data;
        return this.$message.success("获取角色列表成功");
      }
    },
    // 移除角色权限
    async removeRightById(roles, id) {
      const confirmResult = await this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("取消了删除");
      } else {
        const { data: res } = await this.$http.delete(`roles/${roles.id}/rights/${id}`);
        if (res.meta.status !== 200) {
          return this.$message.error("删除权限失败!");
        } else {
          // this.getRolesList()
          // 直接调用获取用户的方法会导致展开栏的关闭,这样体验不好
          // 可以直接把返回的最新数据直接赋值
          roles.children = res.data;
          return this.$message.success("删除权限成功!");
        }
      }
    },
    // 添加用户对话框置空
    resetAddRolesDialog() {
      this.$refs.addRolesRef.resetFields();
    },
    // 添加用户权限
    addRoles() {
      this.$refs.addRolesRef.validate(async (valid) => {
        if (!valid) {
          return;
        } else {
          const { data: res } = await this.$http.post("roles", this.addRolesDialogForm);
          if (res.meta.status !== 201) {
            return this.$message.error("添加角色失败");
          }
          this.dialogVisible.addRolesDialogVisible = false;
          this.getRolesList();
          return this.$message.success("添加角色成功");
        }
      });
    },
    // 编辑用户对话框置空
    resetEditRolesDialog() {
      this.$refs.editRolesRef.resetFields();
    },
    // 编辑用户对话框显示
    async setEditRolesDialogVisible(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return;
      } else {
        this.editRolesDialogForm = res.data;
        this.dialogVisible.editRolesDialogVisible = true;
      }
    },
    // 编辑用户
    editRoles() {
      // 验证
      this.$refs.editRolesRef.validate(async (valid) => {
        if (!valid) {
          return;
        } else {
          // 发送请求
          await this.$http
            .put("roles/" + this.editRolesDialogForm.roleId, {
              roleName: this.editRolesDialogForm.roleName,
              roleDesc: this.editRolesDialogForm.roleDesc,
            })
            .then((res) => {
              if (res.data.meta.status !== 200) {
                return this.$message.error("编辑角色失败");
              } else {
                this.getRolesList();
                return this.$message.success("编辑角色成功");
              }
            });
          // 关闭对话框
          this.dialogVisible.EditRolesDialogVisible = false;
        }
      });
    },
    // 删除用户
    async deleteRolesById(id) {
      // 声明一个警告弹出框,打印结果都是文本格式，即是string字符串类型
      const confirmRusult = await this.$confirm("此操作将永久删除该文件，是否继续？？？", "永久删除该用户", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      if (confirmRusult !== "confirm") {
        return this.$message.info("已经取消了删除");
      } else {
        // roles后面是有一个/号的
        this.$http.delete("roles/" + id).then((res) => {
          const { data: response } = res;
          if (response.meta.status !== 200) {
            return this.$message.error("删除用户失败");
          } else {
            this.getRolesList();
            return this.$message.success("删除用户成功");
          }
        });
      }
    },
    // 分配权限对话框重置,避免数据复选
    setRightDialogVisibleClosed() {
      this.defKeys = [];
    },
    // 分配用户权限对话框显示
    async showSetRightDialog(roles) {
      // 获取角色id， 之后提交数据分配用户权限用上
      this.rolesId = roles.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("分配用户查询失败");
      } else {
        // 获取到权限列表
        this.rightsList = res.data;
        // 权限数组获取
        this.getLeafKeys(roles, this.defKeys);
        // 展示分配权限对话框
        this.dialogVisible.setRightDialogVisible = true;
        return this.$message.success("分配用户查询成功");
      }
    },
    // 递归形式，获取角色下所有的三级权限id，保存到数组中进行树型结构展示
    getLeafKeys(node, arr) {
      // 没有子级权限，保存id
      if (!node.children) {
        // 数组中保存三级权限id
        return arr.push(node.id);
        // 有子级权限，继续遍历子级权限
      } else {
        node.children.forEach((item) => this.getLeafKeys(item, arr));
      }
    },
    // 分配用户权限
    async allotRights() {
      // 获取所有可以被选择的节点（数组形式）
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()];
      // 分隔字符串
      const idStr = keys.join(",");
      // 发送请求
      const { data: res } = await this.$http.post(`roles/${this.rolesId}/rights`, { rids: idStr });
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败");
      } else {
        // 关闭对话框;
        this.dialogVisible.setRightDialogVisible = false;
        // 重新获取列表
        this.getRolesList();
        return this.$message.success("分配用户成功");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-table {
  padding-top: 30px;
}
.el-tag {
  margin: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
